<?php
include '_init_.php';
define('DATA_CHAR_ENCODE','UTF-8');
//define('CLIENT_CSV_ENCODE','gbk');

 if(SessionUtil::isExistVar(constant('SESSION_KEY_USER_ID')) && 
				(SessionUtil::getVar(constant('SESSION_KEY_USER_IS_ADMIN')) == 'Y'
				))
				{
				}else{
				exit("Not allowed!");
				}
define('CLIENT_CSV_ENCODE','cp950');
//define('CLIENT_CSV_ENCODE','GBK');
if (!function_exists('fputcsv')) {
  function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
    $str = '';
    $escape_char = '\\';
    foreach ($fields as $value) {
      if (strpos($value, $delimiter) !== false ||
          strpos($value, $enclosure) !== false ||
          strpos($value, "\n") !== false ||
          strpos($value, "\r") !== false ||
          strpos($value, "\t") !== false ||
          strpos($value, ' ') !== false) {
        $str2 = $enclosure;
        $escaped = 0;
        $len = strlen($value);
        for ($i=0;$i<$len;$i++) {
          if ($value[$i] == $escape_char) {
            $escaped = 1;
          } else if (!$escaped && $value[$i] == $enclosure) {
            $str2 .= $enclosure;
          } else {
            $escaped = 0;
          }
          $str2 .= $value[$i];
        }
        $str2 .= $enclosure;
        $str .= $str2.$delimiter;
      } else {
        $str .= $value.$delimiter;
      }
    }
    $str = substr($str,0,-1);
    $str .= "\n";
    return fwrite($handle, $str);
  }
}

$condition = isset($_REQUEST[condition])?base64_decode($_REQUEST['condition']):'';


$filename = $_REQUEST['from'].'.'.date('YmdHis').".csv";

header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
 
$out = fopen('php://output', 'w');
//header
$header = array(
'預約門市',
'預約單號',
'門市人員',
'姓名',
'生日',
'電話',
'手機',
'電郵1',
'電郵2',
'地址',
'預約類別',
'數位光碟',
'相本',
'相本數量',
'拍攝人數(成人)',
'拍攝人數(小孩)',
'服裝造型(成人)',
'服裝造型(小孩)',
'尺寸',
'贈品',
'備註',
'拍照日期',
'攝影師',
'造型師',
'看樣日期',
'看樣客服',
'取件日期',
'取件客服',
'款項',
'消費金額',
'已付款項',
'結餘款項'
);
//encode to csv characterset
foreach($header as $index=>$noused)
{
	$header[$index] =  mb_convert_encoding($header[$index],constant('CLIENT_CSV_ENCODE'),constant('DATA_CHAR_ENCODE'));
}
fputcsv($out, $header);

$dtMainIndex = new DataTable(constant('DB_TABLE_ORDER_INDEX_MAIN'));
$orderBy = 'created';

$pageSize = 100;
$recordCount = $dtMainIndex->get_count($condition);
$pageCount = ceil($recordCount/$pageSize);

for($page = 1; $page <= $pageCount; $page++)
{
	$data_list = $dtMainIndex->get_list($condition,$orderBy,$pageSize,($page - 1)*$pageSize);
	foreach($data_list as $orderRow)
	{
		$orderManager = Order_Manager::getOrderManager($orderRow['manager_id']);
		$orderManager->init();
		$orderInfo = $orderManager->getInfo();
		
		$csvLineData = array();
		$csvLineData[] = $orderInfo['department'];
		$csvLineData[] = $orderInfo['number'];
		$csvLineData[] = $orderInfo['department_worker'];
		$csvLineData[] = $orderInfo['customerinfo']['name'];
		$csvLineData[] = sprintf("民國 %s年 %s月 %s日",$orderInfo['customerinfo']['birthday']['year'],$orderInfo['customerinfo']['birthday']['month'],$orderInfo['customerinfo']['birthday']['date']);
		$csvLineData[] = sprintf("(%s)%s",$orderInfo['customerinfo']['tel']['part_one'],$orderInfo['customerinfo']['tel']['part_two']);
		$csvLineData[] = $orderInfo['customerinfo']['mobile'];
		$csvLineData[] = $orderInfo['customerinfo']['email'];
		$csvLineData[] = $orderInfo['customerinfo']['email2'];
		$csvLineData[] = sprintf("%s%s%s",$orderInfo['customerinfo']['address']['part_one'],$orderInfo['customerinfo']['address']['part_two'],$orderInfo['customerinfo']['address']['part_three']);
		$csvLineData[] = $orderInfo['type'];
		$csvLineData[] = $orderInfo['disk_number'];
		$csvLineData[] = $orderInfo['benzu_style'];
		$csvLineData[] = $orderInfo['benzu_number'];
		$csvLineData[] = $orderInfo['person_number'];
		$csvLineData[] = $orderInfo['person_number2'];
		$csvLineData[] = $orderInfo['dress_number'];
		$csvLineData[] = $orderInfo['dress_number2'];
		
		$frameTable = array();
		foreach($orderInfo['zoom_frame_list'] as $tmpIndex=>$tmpData)
		{
			$frameTable[$tmpData['size_id']] = $tmpData['frame_name'];
		}
		$sizeInfo = '';
		foreach($orderInfo['zoom_list'] as $tmpIndex=>$tmpData)
		{
			 $sizeNameMap[$tmpData['size_id']] = $tmpData['size_name'];
			 $sizeInfo .= sprintf("%s吋 X %s %s",$tmpData['size_name'],$tmpData['number'],$frameTable[$tmpData['size_id']]);
			if($tmpData['is_gift'] == 'Y')
			{
				 $sizeInfo .= "(贈品)";
			}
			 $sizeInfo .= "\\n";
		}
		$csvLineData[] =  $sizeInfo;
		
		$giftList = '';
		foreach($orderInfo['gift_list'] as $tmpIndex=>$tmpData)
		{
			$giftList .= sprintf("%s X %s",$tmpData['gift_name'],$tmpData['number']);
			if($tmpData['is_gift'] == 'Y')
			{
				 $giftList .= "(贈品)";
			}
			 $giftList .= "\\n";
		}
		$csvLineData[] =  $giftList;
		
		$noteStr = '';
		if($orderInfo['note_list'])
		{	
			foreach($orderInfo['note_list'] as $itIndex=>$tmpData)
			{
				$noteStr .= sprintf("%s-%s\\n", date(constant('WEBSITE_DATE_TIME_FORMATE'),strtotime($tmpData['date'])),$tmpData['content']);
			}
		}
		$csvLineData[] = $noteStr;
		
		if(strlen($orderInfo['workflow']['photo_time']) > 0)
		{
			$csvLineData[] = date(constant('WEBSITE_DATE_TIME_FORMATE'),strtotime($orderInfo['workflow']['photo_time']));
		}else{
			$csvLineData[]  = '';
		}
		$csvLineData[]  = implode($orderInfo['workflow']['photo_person_list'],',');
		$csvLineData[]  = implode($orderInfo['workflow']['dress_person_list'],',');
		
		if(strlen($orderInfo['workflow']['proof_time']) > 0)
		{
			$csvLineData[] = date(constant('WEBSITE_DATE_TIME_FORMATE'),strtotime($orderInfo['workflow']['proof_time']));
		}else{
			$csvLineData[]  = '';
		}
		$csvLineData[]  = implode($orderInfo['workflow']['csr_list'],',');
	
		if(strlen($orderInfo['workflow']['pickup_time']) > 0)
		{
			$csvLineData[] = date(constant('WEBSITE_DATE_TIME_FORMATE'),strtotime($orderInfo['workflow']['pickup_time']));
		}else{
			$csvLineData[]  = '';
		}
		$csvLineData[]  = implode($orderInfo['workflow']['pickup_person_list'],',');
		
		$payList = '';
		foreach($orderInfo['pay_list'] as $index=>$tmpData)
		{
			if($tmpData['discount'])
			{
				$payList .= sprintf("%s(折扣)",$tmpData['discount']['type']);
			}else{
				$payList .= $tmpData['type'];
			}
			$payList .=  sprintf(" %s NT.%s",date(constant('WEBSITE_DATE_TIME_FORMATE'),strtotime($tmpData['date'])),$tmpData['amount']);
			if(isset($tmpData['csr']) && strlen($tmpData['csr']) > 0)
			{
				$payList .=  $tmpData['csr'];
			}
			if(isset($tmpData['sales']) && strlen($tmpData['sales']) > 0)
			{
				$payList .=  $tmpData['sales'];
			}
			$payList .= "\\n";
		}
		$csvLineData[]  = $payList;
		$csvLineData[]  = $orderInfo['price']['total'];
		$csvLineData[]  = $orderInfo['price']['pre_pay'];
		$csvLineData[]  = $orderInfo['price']['need_pay'];
		
		//encode to csv characterset
		foreach($csvLineData as $index=>$noused)
		{
			$csvLineData[$index] =  mb_convert_encoding($csvLineData[$index],constant('CLIENT_CSV_ENCODE'),constant('DATA_CHAR_ENCODE'));
		}
		
		
		fputcsv($out,$csvLineData);
		unset($orderInfo);
	}
	unset($data_list);
}

fclose($out);
?>